package cn.virens.common.util.core.network;

import cn.virens.common.util.exception.APIException;
import cn.virens.common.util.exception.ExceptionUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;

import java.nio.charset.Charset;

public class AjaxResUtil {
    private static final Charset charset = Charset.forName("UTF-8");

    public static void failure(ServletRequest req, ServletResponse resp, String message) {
        write(req, resp, "ERROR", message);
    }

    public static void success(ServletRequest req, ServletResponse resp, String message) {
        write(req, resp, "SUCCESS", message);
    }

    public static void write(ServletRequest req, ServletResponse resp, Exception exception) {
        write(req, resp, ExceptionUtil.c(exception), ExceptionUtil.m(exception));
    }

    public static void write(ServletRequest request, ServletResponse response, String code, String message) {
        ExceptionUtil.e2(formatResponseToBytes(code, message), responseBytes -> {
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                HttpServletResponse resp = (HttpServletResponse) response;

                resp.setHeader("Content-Length", String.valueOf(responseBytes.length));
                resp.setHeader("Content-Type", "application/json;charset=utf-8");

                // 输出内容
                outputStream.write(responseBytes);
                outputStream.flush();
            }
        });
    }

    private static byte[] formatResponseToBytes(String code, String message) throws APIException {
        return ("{\"code\":\"" + code + "\"" + ",\"message\":\"" + message + "\"}").getBytes(charset);
    }
}
